import React, { useRef, useState } from 'react';
import _ from 'lodash';
import { connect } from 'umi';
import { Button, Tooltip, Popconfirm, message } from 'antd';
import * as AntIcons from '@ant-design/icons';
import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  InfoCircleOutlined,
  ControlOutlined,
} from '@ant-design/icons';
import CommonTable from '@/components/CommonTable';
import DebounceWrapper from '@/components/DebounceWrapper';
import ResourceDialog from './components/resourceDialog';
import ResourceActionDialog from './components/resourceActionDialog';
import { fetchResourceTree, deleteResource, batchDeleteResource } from '@/services/system/resource';

const DebounceButton = DebounceWrapper(Button);
// 资源树添加序号
const addTreeIndex = (tree = [], indexString = '', arr = []) => {
  if (!tree.length) return [];
  tree.forEach((item, index) => {
    const node = { ...item };
    delete node.children;
    const currentIndex = indexString ? `${indexString}-${index + 1}` : index + 1;
    node.customIndex = currentIndex;
    if (item.children && item.children.length) {
      node.children = [];
      arr.push(node);
      addTreeIndex(item.children, currentIndex, node.children);
    } else {
      arr.push(node);
    }
  });
  return arr;
};

export default connect(({ global }) => ({ primaryColor: global.primaryColor }))(
  ({ primaryColor }) => {
    const tableRef = useRef(null);
    const [deleteLoading, setDeleteLoading] = useState(false);
    const [deleteLoadingIds, setDeleteLoadingIds] = useState([]);
    const [resourceFormOptions, setResourceFormOptions] = useState({});
    const [resourceFormVisible, setResourceFormVisible] = useState(false);
    const [resourceMenuActionModalOptions, setResourceMenuActionModalOptions] = useState({});

    // 切换loading
    const toggleDeleteLoading = (id, status) => {
      setDeleteLoadingIds((list) => {
        const nextList = [...list];
        if (status) {
          nextList.push(id);
        } else {
          const index = _.indexOf(nextList, id);
          if (index > -1) {
            nextList.splice(index, 1);
          }
        }
        return nextList;
      });
    };

    return (
      <>
        <CommonTable
          ref={tableRef}
          rowKey={'id'}
          rowSelection={{ checkStrictly: false }}
          paging={false}
          header={{
            headerTitle: '资源列表',
            headerToolsRender: true,
            headerButtonList: [
              {
                key: 'add',
                type: 'primary',
                label: '新增',
                icon: <PlusOutlined />,
              },
              {
                key: 'delete',
                danger: true,
                type: 'primary',
                label: '批量删除',
                loading: deleteLoading,
                confirmText: '确认批量删除所勾选的资源节点数据?',
                icon: <DeleteOutlined />,
              },
            ],
            headerButtonClick: async ({ key }) => {
              switch (key) {
                case 'add':
                  setResourceFormVisible(true);
                  break;
                case 'delete':
                  const { refresh, getSelectedList } = tableRef.current;
                  if (getSelectedList) {
                    const selectedList = getSelectedList();
                    if (selectedList && selectedList.length) {
                      setDeleteLoading(true);
                      try {
                        await batchDeleteResource({ ids: _.map(selectedList, 'id') });
                        refresh && refresh();
                        message.success('资源数据批量删除成功');
                      } catch (e) {
                        console.log('删除失败');
                      }
                      setDeleteLoading(false);
                    } else {
                      message.warning('请至少选择一项数据后再操作');
                    }
                  }
                  break;
              }
            },
          }}
          request={async (params) => {
            const records = await fetchResourceTree(params);
            return { data: addTreeIndex(records) };
          }}
          columns={[
            {
              title: '序号',
              dataIndex: 'customIndex',
              align: 'left',
            },
            {
              title: '资源图标',
              dataIndex: 'menuIcon',
              width: 96,
              render: (iconName) =>
                iconName
                  ? React.createElement(
                      AntIcons[iconName],
                      _.assign(
                        { style: { fontSize: 18 } },
                        /TwoTone$/.test(iconName) ? { twoToneColor: primaryColor } : {},
                      ),
                    )
                  : '无',
            },
            { title: '资源标题', dataIndex: 'title' },
            {
              title: '资源类型',
              dataIndex: 'type',
              columnControl: { typeList: 'transfer', filterDictType: 'resource_type' },
            },
            {
              title: '资源状态',
              dataIndex: 'resStatus',
              columnControl: { typeList: 'transfer', filterDictType: 'res_status' },
            },
            {
              title: '资源描述',
              dataIndex: 'description',
            },
            {
              title: (
                <>
                  操作
                  <Tooltip placement="top" title={'类型是菜单的资源可配置按钮/接口管理'}>
                    <InfoCircleOutlined className="tooltip-information-handle-icon" />
                  </Tooltip>
                </>
              ),
              dataIndex: 'id',
              fixed: 'right',
              width: 280,
              render: (text, data) => {
                const isMenu = data.type === '2';
                const deleteLoading = _.includes(deleteLoadingIds, text);
                return (
                  <>
                    <DebounceButton
                      type="link"
                      size="small"
                      icon={<EditOutlined />}
                      disabled={deleteLoading}
                      onClick={() => {
                        setResourceFormOptions(data);
                        setResourceFormVisible(true);
                      }}
                    >
                      查看/编辑
                    </DebounceButton>
                    <DebounceButton
                      type="link"
                      size="small"
                      icon={<ControlOutlined />}
                      disabled={deleteLoading || !isMenu}
                      onClick={() => {
                        setResourceMenuActionModalOptions({
                          resourceId: text,
                          path: data.routePath,
                          title: data.title,
                        });
                      }}
                    >
                      按钮/接口
                    </DebounceButton>
                    <Popconfirm
                      okText="确定"
                      cancelText="取消"
                      title={`确认删除该${isMenu ? '菜单' : '目录'}节点，删除后不可恢复`}
                      placement="topRight"
                      onConfirm={async () => {
                        toggleDeleteLoading(text, true);
                        try {
                          await deleteResource({ id: text });
                          const { refresh } = tableRef.current;
                          refresh && refresh();
                          message.success(`${isMenu ? '菜单' : '目录'}节点删除成功`);
                        } catch (e) {
                          console.log('删除失败');
                        }
                        toggleDeleteLoading(text, false);
                      }}
                    >
                      <DebounceButton
                        danger
                        type="link"
                        size="small"
                        icon={<DeleteOutlined />}
                        loading={deleteLoading}
                      >
                        删除
                      </DebounceButton>
                    </Popconfirm>
                  </>
                );
              },
            },
          ]}
        />
        <ResourceDialog
          options={resourceFormOptions}
          visible={resourceFormVisible}
          closeModal={() => {
            setResourceFormOptions({});
            setResourceFormVisible(false);
          }}
          updateList={() => {
            const { refresh } = tableRef.current;
            refresh && refresh();
          }}
        />
        <ResourceActionDialog
          visible={!_.isEmpty(resourceMenuActionModalOptions)}
          options={resourceMenuActionModalOptions}
          closeModal={() => {
            setResourceMenuActionModalOptions({});
          }}
        />
      </>
    );
  },
);
